package elitech.vietnam.weatherfashion;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.ImageHelper;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.ImageUploader;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class EditPostActivity extends Activity implements OnClickListener {

	private EditText textbox_content;
	private ImageView image_post;
	private Button button_save;

	String image_path;
	int postId, memId;
	String postContent;
	String path = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_post);

		image_path = getIntent().getStringExtra("PostImage");
		postId = getIntent().getIntExtra("PostID", -1);
		memId = getIntent().getIntExtra("MemID", -1);
		postContent = getIntent().getStringExtra("PostContent");

		textbox_content = (EditText) findViewById(R.id.newpost_textbox_content);
		image_post = (ImageView) findViewById(R.id.newpost_image);
		button_save = (Button) findViewById(R.id.newpost_button_save);
		//button_editpic = (Button) findViewById(R.id.editpost_button_editpic);

		button_save.setOnClickListener(this);
		//button_editpic.setOnClickListener(this);

		UrlImageViewHelper.setUrlDrawable(image_post, Const.SERVER_IMAGE_URL + image_path);
		textbox_content.setText(postContent);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_content.getWindowToken(), 0);
		switch (v.getId()) {
		case R.id.newpost_button_save:
			if (postId > 0 && memId > 0) {
				new EditPostTask().execute();
			}
			break;

		case R.id.editpost_button_editpic:
			MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
			if (user == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				startActivity(intent);
			} else
				new PicPickerDialog(this).show();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		int n = requestCode & 0xffff;
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;

		switch (n) {

		case MainActivity.REQ_CODE_LIB:
			path = Utils.getPath(data.getData(), this);
			break;

		case MainActivity.REQ_CODE_CAM:
			path = NewPostActivity.CAM_PATH;
			break;

		default:
			break;
		}

		if (path == null || path.equals(""))
			Toast.makeText(this, getString(R.string.newpost_failed), Toast.LENGTH_LONG).show();
		else {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle(getString(R.string.processing));
			dialog.setMessage(getString(R.string.please_wait_));
			dialog.show();
			if (ImageHelper.rotateImage(path, NewPostActivity.CAM_PATH))
				path = NewPostActivity.CAM_PATH;
			System.gc();
			ImageHelper.displayThumbImage(image_post, path);
			image_path = "";
			dialog.dismiss();
		}

	}

	class PicPickerDialog extends Dialog implements View.OnClickListener {

		public PicPickerDialog(Context context) {
			super(context);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.layout_dialogcamera);
			((Button) findViewById(R.id.dialogcamera_button_camera)).setOnClickListener(this);
			((Button) findViewById(R.id.dialogcamera_button_gallery)).setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			Intent intent = null;
			int req = 0;
			switch (v.getId()) {
			case R.id.dialogcamera_button_camera:
				intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(NewPostActivity.CAM_PATH)));
				req = MainActivity.REQ_CODE_CAM;
				break;

			case R.id.dialogcamera_button_gallery:
				intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				req = MainActivity.REQ_CODE_LIB;
				break;

			default:
				break;
			}

			if (intent != null)
				startActivityForResult(intent, req);
			dismiss();
		}
	}

	class EditPostTask extends AsyncTask<Integer, Integer, Boolean> {
		ProgressDialog pDialog;

		@Override
		protected Boolean doInBackground(Integer... params) {
			boolean uploadOk = false;
			if (image_path.equals("")) {
				MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
				image_path = user.getId() + "_" + System.currentTimeMillis() + ".jpg";
				ImageUploader imageUploader = new ImageUploader();
				uploadOk = imageUploader.upload(path, image_path);
				if (!uploadOk)
					return false;
				image_path = "member_image/" + image_path;
			}
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				uploadOk = appService.updatePostMember(memId, postId, textbox_content.getText().toString(), image_path);
			} catch (IOException e) {
				uploadOk = false;
			}
			return uploadOk;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(EditPostActivity.this);
			pDialog.setTitle(getString(R.string.processing));
			pDialog.setMessage(getString(R.string.please_wait_));
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			Intent intent = new Intent();
			if (result) {
				Toast.makeText(EditPostActivity.this, getString(R.string.newpost_success), Toast.LENGTH_SHORT).show();
				intent.putExtra("EditPostResult", true);
			} else {
				Toast.makeText(EditPostActivity.this, getString(R.string.newpost_failed), Toast.LENGTH_SHORT).show();
				intent.putExtra("EditPostResult", false);
			}
			setResult(Activity.RESULT_OK, intent);
			finish();
		}
	}
}
